package ch02.Jianda;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class Jianda3 {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, TransformerException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse("src/ch02/scores.xml");

        NodeList student = doc.getElementsByTagName("student");
        for (int i = 0; i < student.getLength(); i++) {
            if (student.item(i).getNodeType() == Node.ELEMENT_NODE) {
                Element item = (Element) student.item(i);
                String id = item.getAttribute("id");
                if (id.equals("1")) {
                    Element item1 = (Element) item.getChildNodes().item(5);
                    item1.getParentNode().removeChild(item1);
                }
                if (id.equals("2")){
                    Element item1 = (Element) item.getChildNodes().item(5);
                    item1.setTextContent("60");
                }
            }
        }

        Element student1 = doc.createElement("student");
        student1.setAttribute("id","3");

        Element name = doc.createElement("name");
        name.setTextContent("三号");
        Element course = doc.createElement("course");
        course.setTextContent("javaWeb");
        Element score = doc.createElement("score");
        score.setTextContent("100");

        student1.appendChild(name);
        student1.appendChild(course);
        student1.appendChild(score);

        Node scores = doc.getElementsByTagName("scores").item(0);
        scores.appendChild(student1);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource domSource = new DOMSource(doc);
        StreamResult result = new StreamResult(new FileOutputStream("src/ch02/scores.xml"));
        transformer.transform(domSource, result);
    }
}
